{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "#载入库"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()\n",
    "\n",
    "#载入数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(60000, 28, 28)"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "train_images.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_images = train_images.reshape(60000, 28, 28, 1)\n",
    "test_images = test_images.reshape(10000, 28, 28, 1)\n",
    "\n",
    "#维度变换"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(60000, 28, 28, 1)"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "train_images.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_images = train_images / 255\n",
    "test_images = test_images/ 255\n",
    "\n",
    "#归一化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_labels = np.array(pd.get_dummies(train_labels))\n",
    "test_labels = np.array(pd.get_dummies(test_labels))\n",
    "\n",
    "#独热编码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = tf.keras.Sequential()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "model.add(tf.keras.layers.Conv2D(filters = 6,kernel_size = (5,5),input_shape=(28,28,1),activation = \"relu\"))#默认padding='valid'，strides=1\n",
    "model.add(tf.keras.layers.MaxPooling2D(pool_size = (2, 2)))#默认strides=None\n",
    "model.add(tf.keras.layers.Flatten())\n",
    "model.add(tf.keras.layers.Dense(64, activation='sigmoid'))\n",
    "model.add(tf.keras.layers.Dense(10, activation='softmax'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model: \"sequential\"\n",
      "_________________________________________________________________\n",
      "Layer (type)                 Output Shape              Param #   \n",
      "=================================================================\n",
      "conv2d (Conv2D)              (None, 24, 24, 6)         156       \n",
      "_________________________________________________________________\n",
      "max_pooling2d (MaxPooling2D) (None, 12, 12, 6)         0         \n",
      "_________________________________________________________________\n",
      "flatten (Flatten)            (None, 864)               0         \n",
      "_________________________________________________________________\n",
      "dense (Dense)                (None, 64)                55360     \n",
      "_________________________________________________________________\n",
      "dense_1 (Dense)              (None, 10)                650       \n",
      "=================================================================\n",
      "Total params: 56,166\n",
      "Trainable params: 56,166\n",
      "Non-trainable params: 0\n",
      "_________________________________________________________________\n"
     ]
    }
   ],
   "source": [
    "model.summary()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['acc'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 1/10\n",
      "1875/1875 [==============================] - 6s 2ms/step - loss: 0.6135 - acc: 0.8387 - val_loss: 0.1379 - val_acc: 0.9628\n",
      "Epoch 2/10\n",
      "1875/1875 [==============================] - 3s 1ms/step - loss: 0.1168 - acc: 0.9684 - val_loss: 0.0757 - val_acc: 0.9779\n",
      "Epoch 3/10\n",
      "1875/1875 [==============================] - 3s 1ms/step - loss: 0.0715 - acc: 0.9799 - val_loss: 0.0561 - val_acc: 0.9823\n",
      "Epoch 4/10\n",
      "1875/1875 [==============================] - 2s 1ms/step - loss: 0.0495 - acc: 0.9868 - val_loss: 0.0500 - val_acc: 0.9827\n",
      "Epoch 5/10\n",
      "1875/1875 [==============================] - 2s 1ms/step - loss: 0.0388 - acc: 0.9889 - val_loss: 0.0447 - val_acc: 0.9861\n",
      "Epoch 6/10\n",
      "1875/1875 [==============================] - 2s 1ms/step - loss: 0.0313 - acc: 0.9920 - val_loss: 0.0462 - val_acc: 0.9849\n",
      "Epoch 7/10\n",
      "1875/1875 [==============================] - 2s 1ms/step - loss: 0.0223 - acc: 0.9944 - val_loss: 0.0429 - val_acc: 0.9858\n",
      "Epoch 8/10\n",
      "1875/1875 [==============================] - 2s 1ms/step - loss: 0.0198 - acc: 0.9952 - val_loss: 0.0436 - val_acc: 0.9859\n",
      "Epoch 9/10\n",
      "1875/1875 [==============================] - 2s 1ms/step - loss: 0.0171 - acc: 0.9958 - val_loss: 0.0412 - val_acc: 0.9866\n",
      "Epoch 10/10\n",
      "1875/1875 [==============================] - 2s 1ms/step - loss: 0.0143 - acc: 0.9965 - val_loss: 0.0400 - val_acc: 0.9857\n"
     ]
    }
   ],
   "source": [
    "history = model.fit(train_images,train_labels,epochs = 10,validation_data=(test_images,test_labels))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "313/313 [==============================] - 0s 1ms/step - loss: 0.0400 - acc: 0.9857\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[0.04000044986605644, 0.9857000112533569]"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.evaluate(test_images,test_labels)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
